package com.bnlr.lrparking.widget;

import android.app.Dialog;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppInfo;
import com.bnlr.lrparking.model.Location;
import com.bnlr.lrparking.effects.Effectstype;
import com.bnlr.lrparking.util.MyDistanceUtil;
import com.bnlr.lrparking.util.APPUtil;

import java.util.LinkedList;
import java.util.List;

/**
 * @Function: 自定义对话框
 * @Date: 2013-10-28
 * @Time: 下午12:37:43
 * @author Tom.Cai
 */
public class NativeDialog extends Dialog {
	private Context context;

	private EditText editText;
	private TextView positiveButton;
	private LinearLayout lay_apps;

	private List<AppInfo> apps;
	private String msg = "选择您需要打开的应用";
	private String msg_default = "您的手机中没有安装地图导航工具，我们将打开浏览器进行web导航，我们任建议您下载百度或高德地图进行导航";
	private String positiveStr = "继续导航";
	private String negativeStr = "取消";
	private Location loc_now;
	private Location loc_end;
	private ImageView imageView28,imageView29;//差号

	public NativeDialog(Context context, Location loc_now, Location loc_end) {
		super(context, R.style.NativeDialog);
		this.context = context;
		this.loc_now = loc_now;
		this.loc_end = loc_end;
		initApps();
		setMsgDialog();
	}

	/**
	 * 得到手机中的地图应用工具
	 */
	private void initApps() {
		//getMapApps:通过包名获取地图App
		apps = APPUtil.getMapApps(context);
		//只显示前5个应用
		if (apps!=null && apps.size()>5) {
			apps = apps.subList(0, 5);
		}
	}
	View mView;
	private void setMsgDialog() {
		/**
		 * 判断有没有地图app
		 */
		if (apps!=null && apps.size()!=0) {
			mView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_native, null);
			LinkedList<View> views = new LinkedList<View>();
			lay_apps = (LinearLayout) mView.findViewById(R.id.lay_apps);
			imageView28=(ImageView)mView.findViewById(R.id.imageView28);
			lay_apps.setOrientation(LinearLayout.VERTICAL);
			imageView28.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					NativeDialog.this.dismiss();
				}
			});

//    		for (AppInfo app : apps) {
			for (int i = 0; i < apps.size(); i++) {
				AppInfo app = apps.get(i);
				View itemView=LayoutInflater.from(getContext()).inflate(R.layout.item_daohang,null);
				ImageView  img_daohang= (ImageView) itemView.findViewById(R.id.img_daohang);
				TextView  tv_daohang= (TextView) itemView.findViewById(R.id.tv_daohang);

				img_daohang.setBackgroundDrawable(app.getAppIcon());
				tv_daohang.setText(app.getAppName());
				itemView.setOnClickListener(applistener);
				itemView.setTag(app.getPackageName());
				//定义左右边距15
//				LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//				para.setMargins(45, 0, 45, 0); // left,top,right, bottom
//				para.gravity = Gravity.CENTER;
//				TextView textView = new TextView(context);
//				app.getAppIcon().getBounds().width();
//				app.getAppIcon().getBounds().height();
//				textView.setCompoundDrawablesWithIntrinsicBounds(null,app.getAppIcon(), null, null);	//设置图标
//				textView.setCompoundDrawablePadding(15);
//				textView.setText(app.getAppName());								//设置文字
//				textView.setTextAppearance(context, R.style.Font12_gary);
//				textView.setLayoutParams(para);									//设置边距
//				textView.setGravity(Gravity.CENTER_HORIZONTAL);					//设置图标文字水平居中
//				textView.setSingleLine(true);
//				textView.setEllipsize(TruncateAt.END);							//设置超出长度显示省略…
//				textView.setMaxEms(6);											//设置最大长度
//				textView.setTag(app.getPackageName());							//设置包名为tag
//				textView.setOnClickListener(applistener);						//设置监听

				views.add(itemView);

				if (views.size()==3 || i==apps.size()-1) {
					LinearLayout.LayoutParams para_lay = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					para_lay.setMargins(0, 30, 0, 0); // left,top,right, bottom
					para_lay.gravity = Gravity.CENTER;

					LinearLayout row = new LinearLayout(context);
					row.setOrientation(LinearLayout.HORIZONTAL);
					row.setGravity(Gravity.CENTER_HORIZONTAL);
					row.setLayoutParams(para_lay);
					for (View view : views) {
						row.addView(view);
					}
					lay_apps.addView(row);
					views.clear();
				}
			}
		}else {
			mView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_native_default, null);
			positiveButton = (TextView) mView.findViewById(R.id.positiveButton);
			imageView29=(ImageView)mView.findViewById(R.id.imageView29);
			if(positiveButton!=null) positiveButton.setText(positiveStr);
			if(positiveButton!=null) positiveButton.setOnClickListener(weblistener);
			imageView29.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					NativeDialog.this.dismiss();
				}
			});
		}

		super.setContentView(mView);
	}
	Effectstype type;
	@Override
	public void show() {
		super.show();
		Window dialogWindow = this.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		/////////获取屏幕宽度
		DisplayMetrics dm = new DisplayMetrics();
		WindowManager wm = (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE);
		wm.getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;
		dialogWindow.setWindowAnimations(R.style.dialog_anim_style);
		/////////设置高宽
		lp.width = (int) (screenWidth * 0.85); // 宽度
		dialogWindow.setAttributes(lp);
	}

	public View getEditText(){
		return editText;
	}

	@Override
	public void setContentView(int layoutResID) {
	}

	@Override
	public void setContentView(View view, LayoutParams params) {
	}

	@Override
	public void setContentView(View view) {
	}

	/**
	 * App图标点击监听，启动app进行导航
	 */
	private View.OnClickListener applistener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			String pak = (String)v.getTag();
			if("com.baidu.BaiduMap".equals(pak)){
				APPUtil.startNative_Baidu(context,loc_now, loc_end);
				Log.e("000",loc_now+"-------"+loc_end);
			}else if("com.autonavi.minimap".equals(pak)){
				APPUtil.startNative_Gaode(context,bd_decrypt(loc_end.getLat(), loc_end.getLng()));
			}else if("com.tencent.map".equals(pak)){
				APPUtil.startNative_Tengxun(context,map_bd2hx(loc_now.getLat(),loc_now.getLng()), map_bd2hx(loc_end.getLat(),loc_end.getLng()));
			}
			NativeDialog.this.dismiss();
		}
	};
	public static Double PI = 3.14159265358979324;
	public static Double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	private Location bd_decrypt(double bd_lat, double bd_lon)
	{
		Location loc;
		double  gg_lat;
		double gg_lon;
		double x = bd_lon - 0.0065, y = bd_lat - 0.006;
		double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y *  x_pi);
		double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		gg_lon = z * Math.cos(theta);
		gg_lat = z * Math.sin(theta);
		loc=new Location(gg_lat,gg_lon);
		return loc;

	}
	/**
	 * 坐标转换，百度地图坐标转换成腾讯地图坐标
	 * @param lat  百度坐标纬度
	 * @param lon  百度坐标经度
	 * @return 返回结果：纬度,经度
	 */
	public static  Location map_bd2hx(double lat, double lon){
		double tx_lat;
		double tx_lon;
		Location loc;
		double x_pi=3.14159265358979324;
		double x = lon - 0.0065, y = lat - 0.006;
		double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		tx_lon = z * Math.cos(theta);
		tx_lat = z * Math.sin(theta);
		loc=new Location(tx_lat,tx_lon);
		return loc;
	}
	/**
	 * 启动web进行导航
	 *
	 */
	private View.OnClickListener weblistener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {

			//###########################################
			//第一种方式：这种方式需要导入百度sdk，才能进行启调，如果没导入会找不到类
			//建议使用这种方式，对浏览器的兼容更好。
			//注释掉这里段代码，取消下面第二种方式的注释可以启用第二种方式
			NaviParaOption para = new NaviParaOption().startPoint(MyDistanceUtil.entity2Baidu(loc_now)).endPoint(MyDistanceUtil.entity2Baidu(loc_end));
			BaiduMapNavigation.openWebBaiduMapNavi(para, context);
			//###########################################


			//第二种方式：这种方式不需要导入百度sdk，可以直接使用
			//不推建使用这种方式，浏览器兼容问题比较严重，比如qq浏览器会封杀百度的此功能。
			//注释掉这里段代码，取消上面第一种方式的注释可以启用第一种方式
			//###########################################
			//String url = APPUtil.getWebUrl_Baidu(loc_now, loc_end);
			//Intent intent = new Intent(Intent.ACTION_VIEW);
			//intent.setData(Uri.parse(url));
			//context.startActivity(intent);
			//###########################################


			NativeDialog.this.dismiss();
		}
	};
}
